<?php

namespace App\Http\Controllers\Api\Sentence;

use App\Enums\Api\Response;
use App\Http\Controllers\Controller;
use App\Models\Category\Category;
use App\Models\Category\CategoryModule;
use App\Models\Sentence\Sentence;
use App\Models\Tool\FileUrl;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use App\Models\Data\ClickLearn;
class SentenceController extends Controller
{
    public function list(Request $request): JsonResponse
    {
        $unitList = Category::query()->select('id', 'name', 'unit_main_name')->where('parent_id', $request->input('gradeId'))->has('sentence.click_learn')->get()->toArray();
        return apiResponse(code: Response::SERVICE_SUCCESS->value, data: $unitList, msg: Response::SERVICE_SUCCESS->response(), type: 'sentence');
    }

    public function show(int $categoryId): JsonResponse
    {
        if ( !Sentence::query()->where('category_id', $categoryId)->with('click_learn')->exists() ) {
            return apiResponse(code:Response::SYSTEM_DATA_NOT_EXISTS->value,data:[],msg: Response::SYSTEM_DATA_NOT_EXISTS->response(),type: 'virtual_page');
        }
        $gradeId=Category::query()->where('id',$categoryId)->value('parent_id');
        $file_url=FileUrl::query()->where('module',CategoryModule::ModuleTypeThree)->first();

        $sentence = Sentence::query()->where('category_id', $categoryId)->with('click_learn')->get()->toArray();
        $data=array_map(function ($item)use($file_url,$gradeId,$categoryId) {
            $value['click_id']=$item['click_learn']['id'];
            $value['content']=$item['click_learn']['content'];
            $value['translation']=$item['click_learn']['translation'];
            $value['practice_translation']=$item['click_learn']['practice_translation'];
            $value['audio_url']=convert_file_address_exist(module:CategoryModule::ModuleTypeTwo,file_address:$item['click_learn']['audio_url'],grade:$gradeId,category:$categoryId,type: '.mp3',file_url: $file_url);
            $value['phonetic']=$item['click_learn']['phonetic']??'';
            $value['type']=$this->type_convert($item['click_learn']['type']);
            return $value;
        },$sentence);
        return apiResponse(code: Response::SERVICE_SUCCESS->value, data: $data, msg: Response::SERVICE_SUCCESS->response(), type: 'sentence');
    }
    public function type_convert(int $type): string
    {
        return match ($type) {
            ClickLearn::TYPE_SENTENCE => 'sentence',
            default => 'word',
        };
    }
}
